<template>
	<view class="page-make-photo-save">
		<photo-info :detailInfo="{
			...detailInfo,
			photoUrl,
			beautyPhotoUrl,
			typesetUrl,
		}" :imageUrlAttr="imageUrlAttr" />
		<u-gap height="10" bgColor="rgba(245, 245, 245, 1)"></u-gap>
		<view class="service-info">
			<view class="service-title">
				<text>选择服务</text>
			</view>
			<view class="detail-item" v-for="item in filterServiceList" :key="item.id" @tap="onServiceChange(item)">
				<view class="flex-between-center">
					<text>{{ item.name }}</text>
					<view class="flex-center">
						<text class="origin-price">&yen;{{ item.amount }}</text>
						<text class="mr-4">&yen;{{ item.discount }}</text>
						<image class="radio-icon" v-if="service.id === item.id" src="/static/other/radio-checked.svg">
						</image>
						<image class="radio-icon" v-else src="/static/other/radio-uncheck.png"></image>
					</view>
				</view>
				<view class="extra-content" v-if="item.remark">
					<image class="sub-radio-icon mr-4" src="/static/other/radio-checked.svg" />
					<text>{{ item.remark }}</text>
				</view>
			</view>

			<view class="desc">
				<text>*支付成功后，下载的电子照会自动去除水印</text>
			</view>
		</view>
		<u-gap height="10" bgColor="rgba(245, 245, 245, 1)"></u-gap>

		<view class="share-info flex-between-center">
			<view class="share-item flex-between-center" v-for="item in shareList" :key="item.id" @click="toShare">
				<view class="share-item-left">
					<view class="share-item-title">{{ item.title }}</view>
					<view class="share-item-desc">{{ item.desc }}</view>
					<view class="share-item-children">{{ item.children }}</view>
				</view>
				<view class="share-item-right">
					<text class="free-text">免费</text>
				</view>
				<image class="share-icon" src="/static/other/click-share.svg"></image>
			</view>
		</view>
		<u-gap height="10" bgColor="rgba(245, 245, 245, 1)"></u-gap>

		<view class="save-multi-background" v-if="showSaveMultiCOlor">
			<view class="service-title flex-start-center-gap-5">
				<text>保存多底色</text>
				<view class="hot-tag">87.3%人选择</view>
			</view>
			<view class="detail-item" @tap="onTapSaveColor">
				<view class="flex-between-center">
					<view class="background-list">
						<view class="background-item" :style="{ background: item.background }"
							v-for="item in backColorList" :key="item.id">
						</view>
					</view>
					<view class="flex-center">
						<text class="origin-price">&yen;{{ service.bkAmount }}</text>
						<text class="mr-4">&yen;{{ service.bkDiscount }}</text>
						<image class="radio-icon" v-if="saveMultiColor" src="/static/other/radio-checked.svg">
						</image>
						<image class="radio-icon" v-else src="/static/other/radio-uncheck.png"></image>
					</view>
				</view>
			</view>
		</view>

		<view class="pay-box">
			<view class="text-box">
				<text>应付款：</text>
				<text class="amount">&yen;{{ payAmount / 100 }}</text>
			</view>
			<view class="custom-button" @tap="onPay">
				<u-button type="primary" shape="circle" text="支付并保存"></u-button>
			</view>
		</view>
	</view>
	<custom-pay-popup v-model:show="showPayPopup" :payAmount="payAmount" @pay="onConfirmPay"
		@paySuccess="onPaySuccess" />
</template>

<script setup>
	import CustomPayPopup from "@/components/custom-pay-popup/custom-pay-popup.vue";
	import photoInfo from '@/components/photo-info/photo-info.vue';
	import {
		onLoad,
		onShareAppMessage,
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		computed,
	} from "vue";
	import {
		backColorList,
		payType,
		directPayPlatforms,
	} from '@/common/js/data.js';
	import {
		queryPackageApi,
		savePhoto,
		saveAllPhoto,
		getPaymentType,
	} from '@/common/js/method.js';

	const serviceList = ref([]);
	const shareCount = ref("0");
	const detailInfo = reactive({
		id: '',
		custom: false, //是否为自定义尺寸
		widthPixel: '-',
		heightPixel: '-',
		photoKey: '',
		beautyPhotoKey:'',
		minSize: '-',
		maxSize: '-',
		backColor: '',
		dpi:'',
	});
	const saveUrl = ref('');
	const photoUrl = ref('');
	const beautyPhotoUrl = ref('');
	const typesetUrl = ref('');
	const service = ref({});
	const busiType = ref("make-photo");
	const loginProvider = uni.getStorageSync('loginProvider');

	const toShare = () => {
		uni.navigateTo({
			url: '/pages/share/share',
		})
	}
	// 是否显示保存多底色
	const showSaveMultiCOlor = computed(() => {
		return busiType.value !== 'photo-cut';
	});

	// 计算支付金额（所有服务的折扣价之和）
	const payAmount = computed(() => {
		let {
			discount,
			bkDiscount
		} = service.value
		const bkDiscountOrZero = saveMultiColor.value ? bkDiscount : 0;
		if (!discount) discount = 0;
		return Number(discount * 100) + Number(bkDiscountOrZero * 100);
	});

	// 套餐类型，1-充值套餐，2-保存电子照套餐，3-冲印邮寄套餐，4-快递方式套餐 5-照片剪辑套餐，6-换底色套餐，7-黑白上色套餐，8-漫画照套餐，9-素描化套餐，10-画质增强套餐，11-证件照打印，12-生活照打印
	const packType = computed(() => {
		let res;
		if (['make-photo', 'custom'].includes(busiType.value)) { //证件照制作-保存电子照(固定尺寸&&自定义)
			res = 2;
		} else if (busiType.value === 'photo-cut') { //证件照裁剪
			res = 5;
		} else if (busiType.value === 'change-background') { //换底色
			res = 6;
		}
		return res;
	})

	// 下单接口的recordType字段
	//照片类型，1-保存电子照，2-冲印邮寄，3-证件照裁剪，4-换底色套餐，5-人像素描照，6-人像漫画照，7-黑白上色照，8-老照片修复，9-修改DPI，10-图片格式转换,11-证件照打印，12-生活照打印
	const recordType = computed(() => {
		let res;
		if (['make-photo', 'custom'].includes(busiType.value)) { //证件照制作-保存电子照(固定尺寸&&自定义)
			res = 1;
		} else if (busiType.value === 'photo-cut') { //证件照裁剪-保存电子照
			res = 3;
		} else if (busiType.value === 'change-background') { //换底色-保存电子照
			res = 4;
		}
		return res;
	})

	const singleName = computed(() => {
		if (['make-photo'].includes(busiType.value)) { //新
			return '保存普通电子照';
		} else { //旧
			return '保存单张电子照';
		}
	})
	const typesetName = computed(() => {
		if (['make-photo'].includes(busiType.value)) { //新
			return '保存高清排版照';
		} else { //旧
			return '保存排版电子照';
		}
	})
	const shareList = computed(() => {
		return [{
				id: "1",
				title: "分享5次",
				desc: singleName.value,
				children: `${shareCount.value}/5`,
			},
			{
				id: "2",
				title: "分享5次",
				desc: typesetName.value,
				children: `${shareCount.value}/5`,
			},
		];
	});

	// 单张照判断（新、旧）
	const isSingle = (serviceName) => {
		return ['保存单张电子照', '保存普通电子照', '保存高清电子照(推荐)'].includes(serviceName);
	}
	// 普通单张照判断（新、旧）
	const isNormalSingle = (serviceName) => {
		return ['保存单张电子照', '保存普通电子照'].includes(serviceName);
	}

	const imageUrlAttr = computed(() => {
		if (!service.value) return;
		const serviceName = service.value.name;
		const serviceMap = {
			'保存单张电子照': 'photoUrl',
			'保存排版电子照(推荐)': 'typesetUrl',
			
			'保存普通电子照': 'photoUrl',
			'保存高清电子照(推荐)': 'beautyPhotoUrl',
			'保存高清排版照': 'typesetUrl',
		}
		console.log('imageUrlAttr', serviceMap[serviceName]);
		return serviceMap[serviceName];
	});

	const filterServiceList = computed(() => {
		/* 自定义尺寸或者自定义照片只支持单张的 */
		if (detailInfo.custom || busiType.value === 'custom') {
			return serviceList.value.filter(item => isSingle(item.name));
		} else {
			return serviceList.value;
		}
	});

	const onServiceChange = (item) => {
		service.value = item;
	};

	const saveMultiColor = ref(false);
	const onTapSaveColor = () => {
		saveMultiColor.value = !saveMultiColor.value;
		console.log('onTapSaveColor', saveMultiColor.value)
	};

	const showPayPopup = ref(false);

	const onPay = async () => {
				// 直接调支付的平台
		if(directPayPlatforms.includes(loginProvider)){
			let paymentType = await getPaymentType();
			onConfirmPay({
				type: paymentType,
				callback: async(payInfo) => {
					if(+payAmount.value !== 0) {
						let res = await uni.$pay(payInfo);
						onPaySuccess(res);
					} else {
						onPaySuccess(payInfo);
					}
				},
			})
		} else {
			showPayPopup.value = true;
		}
	};
	// 确认支付
	const onConfirmPay = async ({
		type,
		callback,
	}) => {
		// 支付需要的信息
		const payInfo = await getPayInfo(type);
		callback(payInfo)

	}
	const getBusiParams = (type) => {
		const {
			id,
			widthPixel,
			heightPixel,
			photoKey,
			beautyPhotoKey,
			minSize,
			maxSize,
			backColor,
		} = detailInfo;
		let params = {
			packageId: service.value.id, //套餐id
			recordType: recordType.value,
			productId: id, //主键id
			width: widthPixel,
			height: heightPixel,
			payType: payType[type], //支付方式，0-金豆，1-微信，2-支付宝，3-抖音，4-银联
			bkColor: backColor,
			payAmount: payAmount.value,
			photoStyle: 1, //图像格式，1-jpg,2-png,3-jpeg，默认是jpg
			photoSize: [minSize, maxSize].join(','),
			isSelectBkColor: Number(saveMultiColor.value),
		};
		let specParams = {};
		if (busiType.value === 'photo-cut') { //证件照裁剪
			specParams = {
				imageUrl: saveUrl.value, //证件照裁剪的时候，需要传无水印单张图片地址（支付成功不需要发证件照制作，无水印的图在剪辑时已返回）
			}
		} else if (busiType.value === 'make-photo') { //证件照制作
			specParams = {
				photoKey: isNormalSingle(service.value.name) ? photoKey : beautyPhotoKey, //预览或者美颜接口返回的photoKey
			}
		} else { // 其他情况默认传photoKey（换底色）
			specParams = {
				photoKey, //预览接口返回的photoKey
			}
		}
		return {
			...params,
			...specParams,
		};
	}

	// 获取微信支付接口需要的信息
	const getPayInfo = async (type) => {
		console.log('detailInfo', detailInfo)
		const payload = getBusiParams(type);
		let res = await uni.$request('/api/busi/photo/record/addRecord', payload);
		return res.data;
	}

	const toSuccess = () => {
		setTimeout(() => {
			// 支付成功，跳转结果页（复用证件照制作结果页）
			uni.navigateTo({
				url: `/pages/make-photo/make-photo-save-res`,
			});
		}, 1000);
	}


	const onPaySuccess = async ({
		orderNo
	}) => {
		if (busiType.value === 'photo-cut') { //证件照裁剪-保存电子照
			let res = await savePhoto(saveUrl.value)
			uni.showToast({
				title: '已保存到相册',
			})
		} else {
			// 支付成功，获取无水印照片保存
			let res = await uni.$request('/api/busi/photo/take', {
				orderNo,
				orderType: 1,
			});
			await saveAllPhoto(res.data)
		}
		toSuccess();
	};


	// 查询套餐
	// 套餐类型，1-充值套餐，2-保存电子照套餐（证件照），3-冲印邮寄套餐，4-快递方式套餐 5-照片剪辑套餐，6-换底色套餐，7-黑白上色套餐，8-漫画照套餐，9-素描化套餐，10-画质增强套餐，11-证件照打印，12-生活照打印
	const getPackageInfo = async () => {
		let res = await queryPackageApi([packType.value])
		serviceList.value = res[0].data.packageList;
		if (filterServiceList.value.length > 1) {
			service.value = filterServiceList.value[1];
		} else {
			service.value = filterServiceList.value[0];
		}
	}

	const queryShareCount = async () => {
		let res = await uni.$request('/api/user/share/select')
		shareCount.value = res.data.total || 0;
	}


	onLoad((params) => {
		busiType.value = params.type;
		const data = JSON.parse(params.data)
		
		// 给当前页面入参赋值
		for(let key in detailInfo) {
			detailInfo[key] = data[key];
		}
		
		photoUrl.value = decodeURIComponent(data.photoUrl);
		beautyPhotoUrl.value = decodeURIComponent(data.beautyPhotoUrl);
		typesetUrl.value = decodeURIComponent(data.typesetUrl);
		saveUrl.value  = decodeURIComponent(data.saveUrl);
		console.log('onLoad666', detailInfo)
		getPackageInfo();
		queryShareCount();
		
	})
</script>

<style lang="less" scoped>
	.page-make-photo-save {
		box-sizing: border-box;
		padding: 10px 16px 113px 16px;
		height: 100vh;
		overflow-y: auto;
		opacity: 1;
		background: rgba(245, 245, 245, 1);

		.detail-item {
			// display: flex;
			// align-items: center;
			// justify-content: space-between;
			/** 文本 */
			font-size: 14px;
			line-height: 20px;
			color: rgba(56, 56, 56, 1);
		}

		.service-info {
			border-radius: 8px;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.02);
			padding: 16px 16px 16px 16px;
			display: flex;
			flex-direction: column;
			gap: 15px;

			.service-title {
				font-size: 16px;
				font-weight: 700;
				line-height: 24px;
				color: rgba(56, 56, 56, 1);
			}

			.extra-content {
				margin-top: 5px;
				font-size: 12px;
				line-height: 18px;
				color: rgba(69, 144, 229, 1);
				display: flex;
				align-items: center;
				gap: 5px;
			}

			.sub-radio-icon {
				width: 14px;
				height: 14px;
			}
		}

		.share-info {
			gap: 15px;

			.share-item {
				flex: 1;
				border-radius: 8px;
				background: rgba(255, 255, 255, 1);
				box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.02);
				padding: 5px 16px;
				display: flex;
				position: relative;
				border: 0;
				text-align: left;
			}

			.share-item-title {
				font-size: 14px;
				font-weight: 700;
				line-height: 20px;
				color: rgba(56, 56, 56, 1);
			}

			.share-item-desc {
				font-size: 12px;
				line-height: 18px;
				color: rgba(56, 56, 56, 1);
			}

			.share-item-children {
				font-size: 12px;
				line-height: 18px;
				color: rgba(166, 166, 166, 1);
			}

			.share-icon {
				position: absolute;
				right: 0;
				top: 0;
				width: 114rpx;
				height: 32rpx;
			}

			.free-text {
				font-size: 16px;
				font-weight: 700;
				letter-spacing: 0px;
				line-height: 24px;
				color: rgba(212, 48, 48, 1);
			}
		}

		.save-multi-background {
			border-radius: 8px;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.02);
			padding: 16px 16px 16px 16px;
			display: flex;
			flex-direction: column;
			gap: 15px;

			.background-list {
				gap: 10px;
				display: flex;

				.background-item {
					height: 16px;
					width: 16px;
					border-radius: 100%;
					border: 1px solid rgba(229, 229, 229, 1);
				}
			}
		}

		.pay-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			box-sizing: border-box;
			height: 212rpx;
			border-radius: 32rpx 32rpx 0 0;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px -4rpx 12rpx rgba(0, 0, 0, 0.02);
			padding: 32rpx 32rpx 68rpx 32rpx;
			position: fixed;
			left: 0;
			bottom: 0;

			.text-box {
				font-size: 18px;
				line-height: 27px;
				color: rgba(0, 0, 0, 1);

				.amount {
					font-weight: 700;
					color: rgba(69, 145, 230, 1);
				}
			}
		}
	}
</style>